package com.liser.southernstar.ui.activity;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.liser.print.bluetooth.BluetoothClientFactory;
import com.liser.print.bluetooth.BtManager;
import com.liser.print.bluetooth.callback.ConnectCallback;
import com.liser.print.bluetooth.callback.ScanCallback;
import com.liser.print.bluetooth.model.BluetoothBean;
import com.liser.southernstar.R;
import com.liser.southernstar.framework.helper.ToastHelper;
import com.liser.southernstar.framework.ui.BaseActivity;
import com.liser.southernstar.ui.adapter.BluetoothItemAdapter;
import com.qmuiteam.qmui.widget.QMUILoadingView;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListSectionHeaderFooterView;

import java.util.HashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

public class BluetoothActivity extends BaseActivity {

    private static final String TAG = BluetoothActivity.class.getName();

    public static final int REQUEST_ENABLE_BT = 1229;

    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;

    @BindView(R.id.shfv_connected)
    QMUIGroupListSectionHeaderFooterView connectedSectionHeaderFooter;

    @BindView(R.id.qmui_cliv_connected)
    QMUICommonListItemView connectedCommonListItem;

    @BindView(R.id.shfv_searched)
    QMUIGroupListSectionHeaderFooterView searchedSectionHeaderFooter;

    @BindView(R.id.rv_searched)
    RecyclerView searchedRecyclerView;

    @BindView(R.id.bluetoothScan)
    Button bluetoothScan;

    private BluetoothItemAdapter searchedItemAdapter;

    private BluetoothItemAdapter.OnItemClickListener searchedClickListener;

    private CompoundButton.OnCheckedChangeListener connectedCheckedChangeListener;

    private Set<String> macSet = new HashSet<>(16);

    @Override
    protected int onLayout() {
        return R.layout.activity_bluetooth;
    }

    @Override
    protected void onView() {
        initTopBar();
        checkBluetooth();
        initListener(BluetoothActivity.this);
        initView();
        initRecyclerView(BluetoothActivity.this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == Activity.RESULT_OK) {
                // 蓝牙已打开
            } else {
                // 蓝牙未打开
                ToastHelper.show(R.string.bluetooth_is_not_enabled);
            }
        }
    }

    @OnClick(R.id.bluetoothScan)
    public void onBluetoothScan(View view) {
        CharSequence scanText = bluetoothScan.getText();
        if ("扫描".contentEquals(scanText)) {
            searchBluetoothDevices();
        } else if ("停止".contentEquals(scanText)) {
            BtManager.getInstance().stopScan();
        }
    }

    private void initTopBar() {
        mTopBar.addLeftBackImageButton().setOnClickListener(view -> {
            finish();
            overridePendingTransition(R.anim.slide_still, R.anim.slide_out_right);
        });
        mTopBar.setTitle("连接设备");
    }

    /**
     * 检查蓝牙状态
     */
    private void checkBluetooth() {
        boolean enableBluetooth = BtManager.getInstance().isEnableBluetooth();
        if (!enableBluetooth) {
            BtManager.getInstance().enableBluetooth(isOn -> {
                if (isOn) {
                    ToastHelper.show(R.string.open_bluetooth_success);
                } else {
                    ToastHelper.show(R.string.open_bluetooth_fail);
                }
            });
        }
    }

    private void initView() {
        connectedSectionHeaderFooter.setText(getResources().getString(R.string.connected_device));

        connectedCommonListItem.setOrientation(QMUICommonListItemView.VERTICAL);
        connectedCommonListItem.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_SWITCH);
        BluetoothDevice bluetoothDevice = BtManager.getInstance().connectedDevice();
        if (bluetoothDevice != null) {
            macSet.add(bluetoothDevice.getAddress());
            connectedCommonListItem.setText(bluetoothDevice.getName());
            connectedCommonListItem.setDetailText(bluetoothDevice.getAddress());
            connectedCommonListItem.getSwitch().setChecked(true);
        } else {
            connectedCommonListItem.setText(getResources().getString(R.string.device_not_connected));
            connectedCommonListItem.setDetailText("");
        }

        connectedCommonListItem.getSwitch().setOnCheckedChangeListener(connectedCheckedChangeListener);
        connectedCommonListItem.setOnClickListener(view -> {
            // disable掉且不可点击，然后通过整个item的点击事件来toggle开关的状态
            connectedCommonListItem.getSwitch().toggle();
        });

        searchedSectionHeaderFooter.setText(getResources().getString(R.string.device_searched));
    }

    private void initRecyclerView(Context context) {
        VirtualLayoutManager searchedManager = new VirtualLayoutManager(context);
        LayoutHelper searchedHelper = new LinearLayoutHelper();
        searchedRecyclerView.setLayoutManager(searchedManager);
        // 分割线
        searchedRecyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        searchedItemAdapter = new BluetoothItemAdapter(context, searchedHelper);
        // 设置点击监听
        searchedItemAdapter.addOnClickListener(searchedClickListener);
        // 初始化数据
        searchedRecyclerView.setAdapter(searchedItemAdapter);

        Set<BluetoothDevice> bondedDevices = BtManager.getInstance().getBondedDevices();
        if (bondedDevices.size() > 0) {
            for (BluetoothDevice device : bondedDevices) {
                addRecycleItem(device.getAddress(), device.getName());
            }
        }
    }

    private void initListener(Context context) {
        // 列表项点击监听
        searchedClickListener = (view, postion) -> {
            // 连接状态
            if (view instanceof QMUICommonListItemView) {
                QMUICommonListItemView qmuiView = (QMUICommonListItemView) view;
                CharSequence address = qmuiView.getDetailText();
                // 设置Item样式
                qmuiView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
                qmuiView.addAccessoryCustomView(new QMUILoadingView(context));
                // 连接
                connectBluetooth(address.toString(), postion, qmuiView);
            }
        };

        // 切换按钮监听
        connectedCheckedChangeListener = (compoundButton, checked) -> {
            if (!checked) {
                BtManager.getInstance().closeClientSide();
                addRecycleItem(connectedCommonListItem.getDetailText().toString(), connectedCommonListItem.getText().toString());
                connectedCommonListItem.setText(getResources().getString(R.string.device_not_connected));
                connectedCommonListItem.setDetailText("");
            }
        };
    }

    private void searchBluetoothDevices() {
        BtManager.getInstance()
                .startScan(new ScanCallback() {
                    @Override
                    public void onScanStart() {
                        // 开始扫描
                        if (bluetoothScan != null) {
                            bluetoothScan.setText("停止");
                        }
                    }

                    @Override
                    public void onScanStop() {
                        // 搜索完成
                        if (bluetoothScan != null) {
                            bluetoothScan.setText("扫描");
                        }
                    }

                    @Override
                    public void onFindDevice(BluetoothDevice device) {
                        // 搜索到设备
                        String deviceName = device.getName();
                        if (TextUtils.isEmpty(deviceName)) {
                            deviceName = "未知设备";
                        }
                        BluetoothBean bluetoothBean = new BluetoothBean(deviceName, device.getAddress());
                        searchedItemAdapter.addBluetooth(bluetoothBean);
                    }
                });
    }

    private void connectBluetooth(String mac, int postion, QMUICommonListItemView qmuiView) {
        BluetoothDevice remoteDevice = BluetoothClientFactory.getRemoteDevice(mac);
        if (remoteDevice != null) {
            BtManager
                    .getInstance()
                    .connectDevice(remoteDevice, new ConnectCallback() {
                        @Override
                        public void connectSuccess(BluetoothSocket socket, BluetoothDevice device) {
                            // 连接成功
                            qmuiView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_NONE);
                            connectedSuccess(device, postion);
                        }

                        @Override
                        public void connectError(Throwable throwable) {
                            Log.w(TAG, "设备连接失败：", throwable);
                            qmuiView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_NONE);
                            // 连接失败
                            ToastHelper.show("设备连接失败");
                        }

                        @Override
                        public void connectClose(BluetoothDevice device) {

                        }
                    });
        }
    }

    private void connectedSuccess(BluetoothDevice bluetoothDevice, int postion) {
        macSet.remove(bluetoothDevice.getAddress());
        searchedItemAdapter.deleteBluetooth(postion);
        connectedCommonListItem.setText(bluetoothDevice.getName());
        connectedCommonListItem.setDetailText(bluetoothDevice.getAddress());
        connectedCommonListItem.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_SWITCH);
        connectedCommonListItem.getSwitch().setChecked(true);
        ToastHelper.show("设备连接成功");
    }

    private void addRecycleItem(String mac, String name) {
        if (TextUtils.isEmpty(mac)) {
            return;
        }
        boolean notDuplication = macSet.add(mac);
        if (notDuplication) {
            if (TextUtils.isEmpty(name)) {
                name = "未知";
            }
            searchedItemAdapter.addBluetooth(new BluetoothBean(name, mac));
        }
    }

}